package reflect;

import reflect.annotations.AutoRunClass;

import java.io.File;
import java.net.URISyntaxException;

/**
 * 实例化与当前类Test3在同一包中被@AutoRunClass标注的类
 */
public class Test3 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException {


        //获取当前文件类所在的包
        File pathName = new File(
                Test3.class.getResource(".").toURI()
        );
        //获取当前类所在的包名
        String packageName = Test3.class.getPackage().getName();
        //将后缀为".class"的文件添加到数组内
        File[] files = pathName.listFiles(f -> f.getName().endsWith(".class"));
        //遍历数组
        for (File f : files) {
            //截取文件名
            String fileName = f.getName().replace(".class", "");
            //如果该class文件被AutoRunClass注解,则实例化该对象
            Class cls = Class.forName(packageName+"."+fileName);
            if (cls.isAnnotationPresent(AutoRunClass.class)) {
                Object obj = cls.newInstance();
                System.out.println(1);
                System.out.println(obj);
            }
        }

    }
}
